<script setup lang="ts">
import { ref, computed, onUnmounted, onMounted } from 'vue'
import { showToast } from 'vant'
import { data } from '@/assets/data/user.json'
import userCell from '@/components/UserCell.vue'
import { goBack } from '@/assets/utils/function'

const Data = ref(data)

const keyword = ref('')
const searchData = ref({} as any)

const onSearch = (keyword: string) => {
  if (keyword === '') {
    searchData.value = []
    return
  }

  const result = computed(() => {
    return Data.value.filter((item) => item.title.includes(keyword))
  })

  if (result.value.length === 0) {
    searchData.value = []
    showToast({ message: '没有结果' })
    return
  }

  searchData.value = result.value
}

const onCancel = () => {
  goBack()
  keyword.value = ''
  searchData.value = []
}

onMounted(() => {
  console.log('Search组件挂载')
})

onUnmounted(() => {
  console.log('Search组件销毁')
})
</script>

<template>
  <div class="container">
    <van-search
      v-model="keyword"
      show-action
      placeholder="请输入关键字"
      action-text="取消"
      autofocus
      @update:model-value="onSearch"
      @cancel="onCancel"
    />
    <div v-show="Object.keys(searchData).length !== 0">
      <van-cell-group title="联系人">
        <template v-for="item in searchData">
          <userCell v-bind="item" />
        </template>
      </van-cell-group>
    </div>
  </div>
</template>

<style scoped></style>
